package cn.shop.utils;

import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.ibatis.reflection.property.PropertyNamer;

import java.util.Map;

public class QueryUtil {

    /**
     * 根据实体类属性名获取数据库字段名
     *
     * @param column 实体类属性名
     * @return 字段名
     */
    public static <T> String columnToString(SFunction<T, ?> column) {
        LambdaMeta meta = LambdaUtils.extract(column);
        String fieldName = PropertyNamer.methodToProperty(meta.getImplMethodName());
        Class<?> lambdaClass = meta.getInstantiatedClass();
        Map<String, ColumnCache> columnMap = LambdaUtils.getColumnMap(lambdaClass);
        ColumnCache columnCache = columnMap.get(LambdaUtils.formatKey(fieldName));
        return columnCache.getColumn();
    }

}
